package com.jinxin.platform.cdsmsmgr.utils;

import io.netty.util.internal.StringUtil;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Description: bccah
 * Created by 34759 on 2019/8/15 14:15
 */
public class DateUtil {
    public static final String COM_CURRENT_DATE_FORMAT;

    static {
        COM_CURRENT_DATE_FORMAT = "yyyy-MM-dd";
    }

    public static final String COM_CURRENT_DATE_HH_FORMAT = "yyyy-MM-dd HH:mm";

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm";

    public static final String DATE_TIME_PATTERRN = "yyyy-MM-dd HH:mm:ss";

    public static final DateFormat df = new SimpleDateFormat(DEFAULT_PATTERN);
    public static final DateFormat df2 = new SimpleDateFormat(COM_CURRENT_DATE_FORMAT);
    public static final DateFormat df3 = new SimpleDateFormat(COM_CURRENT_DATE_HH_FORMAT);
    public static final DateFormat df4 = new SimpleDateFormat("yyyyMMddHHmmss");

    public static String getTimeStrBySeconds(long timestamp){
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_PATTERRN);
        return sdf.format(new Date(timestamp * 1000));
    }
    //
    public static LocalDateTime timestamToDatetime(int timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * @Desc 获取两个时间之间的间隔天数
     * @param startTime
     * @param endTime
     * @return
     */
    public static int getBetweenDays(Date startTime, Date endTime) {
        int betweenDays = 0;
        long start = startTime.getTime();
        long end = endTime.getTime();

        return (int) (Math.abs(end - start) / (24 * 3600 * 1000));
    }

    public static String getCurrentYMDHMS() {
        return df4.format(new Date());
    }

    public static String getCurrentDayYMD() {

        Calendar seekedDate = Calendar.getInstance();
        seekedDate.setTime(new Date());
        seekedDate.set(Calendar.DAY_OF_MONTH, seekedDate.get(Calendar.DAY_OF_MONTH));

        return df2.format(seekedDate.getTime());
    }

    public static String getSpecifiedDayDate(int field, int daySeek){
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(field, daySeek);
        Date d = c.getTime();
        return df.format(d);
    }

    public static String getYestadyDayYMD() {

        Calendar seekedDate = Calendar.getInstance();
        seekedDate.setTime(new Date());
        seekedDate.set(Calendar.DAY_OF_MONTH, seekedDate.get(Calendar.DAY_OF_MONTH) - 1);

        return df2.format(seekedDate.getTime());
    }

    public static String getCurrentDayYMDHHs() {
        return df3.format(new Date());
    }

    public static Date stringToDate(String dateString) throws ParseException {
        return df3.parse(dateString);
    }

    public static String  getAfterMonth(String inputDate,int number) {
        Calendar c = Calendar.getInstance();//获得一个日历的实例
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try{
            date = sdf.parse(inputDate);//初始日期
        }catch(Exception e){

        }
        c.setTime(date);//设置日历时间
        c.add(Calendar.MONTH,number);
        String strDate = sdf.format(c.getTime());
        return strDate;
    }

    public static String formatDate(String date) throws ParseException {
        if (date == null || "".equals(date)) {
            return "";
        }

        String today = getNextNDay(null, 0);
        String befor1day = getNextNDay(null, -1);
        String befor2day = getNextNDay(null, -2);
        String dateS[] = date.split(" ");

        if (dateS[0].equals(befor1day)) {
            return "昨天 " + dateS[1];
        } else if (dateS[0].equals(befor2day)) {
            return "前天 " + dateS[1];
        } else if (dateS[0].equals(today)) {
            return "今天 " + dateS[1].substring(0, 5);
        }

        return dateS[0];
    }

    public static String getNextNDay(int daySeek) {
        Calendar seekedDate = Calendar.getInstance();
        seekedDate.setTime(new Date());
        seekedDate.set(Calendar.DAY_OF_MONTH, seekedDate.get(Calendar.DAY_OF_MONTH) + daySeek);

        return df2.format(seekedDate.getTime()) + " 00:00:00";
    }

    public static String getNextNDay(String dateString, int daySeek) throws ParseException {
        Calendar seekedDate = Calendar.getInstance();
        if (dateString != null && !"".equals(dateString)) {
            seekedDate.setTime(df.parse(dateString));
        } else {
            seekedDate.setTime(new Date());
        }

        seekedDate.set(Calendar.DAY_OF_MONTH, seekedDate.get(Calendar.DAY_OF_MONTH) + daySeek);

        return df.format(seekedDate.getTime());
    }

    /**
     * 将日期型转换为指定格式的字符串
     *
     * @param date
     *            日期
     * @param format
     *            格式
     * @return
     */
    public static String dateToString(Date date, String format) {
        if (null == format || "".equals(format)) {
            format = "yyyy年MM月dd日 hh点:mm分:ss秒";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }


    public static String genSecurityKey() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replace("-", "");
    }

    public static Date parseStr(String dateStr,String pattern ){
        SimpleDateFormat sim = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = sim.parse(dateStr);
        } catch (ParseException e) {
        }
        return date;
    }

    public static String getRandmon() {
        return genSecurityKey();
    }

    public static int div(int v1, int v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }

        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);

        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).intValue();
    }

    public static float divf(int v1, int v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }

        if (v1 == 0 || v2 == 0) {
            return 0;
        }

        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);

        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    /**
     * 匹配非负整数(正整数 + 0)
     *
     * @param value true:0或正整数 false:负数
     * @return
     */
    private static Pattern nonNgativePattern = Pattern.compile("^[1-9]\\d*|0$");

    public static boolean isNonNegative(Object value) {
        return nonNgativePattern.matcher(String.valueOf(value)).matches();
    }

    /**
     * 匹配正整数
     *
     * @param value true:正整数 false:非正整数
     * @return
     */
    private static Pattern positivePattern = Pattern.compile("^[1-9]\\d*$");

    public static boolean isPositive(Object value) {
        return positivePattern.matcher(String.valueOf(value)).matches();
    }

    /**
     * 验证手机号码
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189
     */
    private static Pattern mobilePhonePattern = Pattern.compile("^1(3|4|5|7|8)\\d{9}$");//"^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$");

    public static boolean isMobilePhone(String value) {
        return mobilePhonePattern.matcher(String.valueOf(value)).matches();
    }

    public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
        String newPattern = format;
        if(StringUtil.isNullOrEmpty(format)){
            newPattern = DATE_TIME_PATTERRN;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(newPattern);
        return localDateTime.format(formatter);
    }

    public static LocalDateTime timeString2LocalDateTime(String timeStr,String pattern){
        if(StringUtil.isNullOrEmpty(timeStr)){
            return LocalDateTime.now();
        }
        if(StringUtil.isNullOrEmpty(pattern)){
            pattern = DATE_TIME_PATTERRN;
        }
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(timeStr,df);
    }

}
